import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Block} from '@tarojs/components'
import {AtIndexes, AtIcon} from 'taro-ui'
import {HotCity, AllCity} from '../../utils/server.interface'
import {location} from '../../utils/location.service'
import {http} from '../../utils/http'
import {SEARCH_CITY, MOVIE_CITY} from '../../constants/api'
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {vcmonitor} from "../../utils/tools";
import './movie-city.scss'

interface StateType {
  hotCity: HotCity[]
  allCity: AllCity[]
  searchKey: string
  searchCity: HotCity[]
  list: any
  relocationLoading: boolean
  location: any
}

type PageStateProps = {}
type PageDispatchProps = {}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface SelectCity {
  props: IProps
}

class SelectCity extends Component {
  state: StateType = {
    hotCity: [],
    allCity: [],
    list: [],
    searchKey: '',
    relocationLoading: true,
    searchCity: [],
    location: {},
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const location = Taro.getStorageSync("Mlocation") || {region_id: 0, area_name: '未知'};
    this.setState({
      location
    })
  }

  async componentDidShow() {
    vcmonitor(this);
    const location = Taro.getStorageSync("Mlocation") || {region_id: 0, area_name: '未知'};
    this.setState({
      location
    })

    Taro.showLoading({title: '加载城市中...'})
    const ret = await http.MGet(MOVIE_CITY, {})
    const {hotCity, allCity} = this.state
    const zm = 'ABCDEFGHJKLMNPQRSTUWXYZ'
    for (let i = 0; i < zm.length; i++) {
      allCity[i] = {
        title: zm[i],
        key: zm[i],
        items: []
      }
    }
    if (ret) {
      ret.map(item => {
        const i = zm.indexOf(item.letter)
        if (i >= 0) {
          allCity[i].items.push({
            area_name: item.city_name,
            name: item.city_name,
            region_id: item.city_id
          })
        }
        if (item.hot == 1) {
          hotCity.push({area_name: item.city_name, region_id: item.city_id})
        }
      })
    }
    //console.log(allCity)
    this.setState({hotCity, allCity, list: ret})
    Taro.hideLoading()
  }

  async search() {
    const searchCity = await http.get(SEARCH_CITY, {keywords: this.state.searchKey})
    if (searchCity) {
      this.setState({searchCity})
    }
  }

  checkCity(str, isOk) {
    const that = this
    const list = that.state.list
    let val = {}
    if (str.indexOf('莱芜') > -1) {
      str = "济南市"
    }
    list.map(item => {
      if (str.indexOf(item.city_name) > -1) {
        val = {region_id: item.city_id, area_name: item.city_name}
      }
    })
    that.setState({
      location: val
    })
    if (isOk) {
      setTimeout(function () {
        that.indexes(val)
      }, 800)
    } else {
      Taro.setStorageSync("Mlocation", val)
    }
  }

  inputChange(value) {
    this.setState({searchKey: value})
  }

  hotCityHandle(item, e) {
    e.stopPropagation()
    this.indexes(item)
  }

  indexes(value) {
    Taro.setStorageSync("Mlocation", value)
    this.naviBack()
  }

  getLocation() {
    try {
      if (process.env.TARO_ENV === 'h5') {
        h5Wx.getLocation(async (res) => {
          const city = await location.getLocationNewH5City(res.longitude, res.latitude, 'wgs84')
          Taro.setStorageSync("ML", {lng: res.longitude, lat: res.latitude})
          if (city) {
            this.checkCity(city.area_name, true)
          }
          this.setState({relocationLoading: true})
        }, 'wgs84')
      } else {
        location.getLocation().then(async (res: any) => {
          if (res == null) {
            console.log('不是微信浏览器');
          } else {
            const city = await location.getLocationCity(res.longitude, res.latitude)
            Taro.setStorageSync("ML", {lng: res.longitude, lat: res.latitude})
            if (city) {
              this.checkCity(city.area_name, false)
            }
          }
        });
      }

    } catch (e) {
      Taro.showModal({
        title: '提示',
        content: '您需要开启手机的GPS定位, 才能为您匹配精准的自提点信息',
        success: (res) => {
        }
      })
    }
  }

  relocation(e) {
    e.stopPropagation()
    const relocationLoading = this.state.relocationLoading
    if (relocationLoading) {
      this.setState({relocationLoading: false})
      try {
        location.getLocation().then(async (res: any) => {
          if (res == null) {
            console.log('不是微信浏览器');
          } else {
            if (process.env.TARO_ENV === 'h5') {
              const city = await location.getLocationNewH5City(res.longitude, res.latitude, 'wgs84')
              Taro.setStorageSync("ML", {lng: res.longitude, lat: res.latitude})
              if (city) {
                this.checkCity(city.area_name, true)
              }
              this.setState({relocationLoading: true})
            } else {
              const city = await location.getLocationCity(res.longitude, res.latitude)
              Taro.setStorageSync("ML", {lng: res.longitude, lat: res.latitude})
              if (city) {
                this.checkCity(city.area_name, true)
              }
              this.setState({relocationLoading: true})
            }
          }
        });
      } catch (e) {
        Taro.showModal({
          title: '提示',
          content: '您需要开启手机的GPS定位, 才能为您匹配精准的信息',
          success: (res) => {
            this.setState({relocationLoading: true})
          }
        })
      }

    }
  }

  naviBack() {
    Taro.navigateBack({
      delta: 1
    })
  }

  clearSearch() {
    this.setState({searchKey: '', searchCity: []})
  }

  render() {
    const {hotCity, allCity, searchCity, location} = this.state
    return (
      <View className='movie-all-city'>
        <GzhAuth />
        <AtIndexes animation onClick={this.indexes.bind(this)} list={allCity}>
          <View className='root'>
            {searchCity.length === 0 && <Block>
              <View className='now-city'>
                <View className='title'>当前定位城市：</View>
                <View className='content'>
                  <View className='location' onClick={this.naviBack.bind(this)}><AtIcon value='map-pin'
                    size='14'
                  /><Text
                    className='city-name'
                  >{location.area_name ? location.area_name : '未知'}</Text>
                  </View>
                  <View className='relocation' onClick={this.relocation.bind(this)}>重新定位</View>
                </View>
              </View>
              <View className='hot-city'>
                <View className='title'>热门城市</View>
                <View className='content'>
                  {hotCity.map((item, index) => <View className='tag-box' key={index}
                    onClick={this.hotCityHandle.bind(this, item)}
                  ><View
                    className='tag'
                  >{item.area_name}</View></View>)}
                </View>
              </View>
            </Block>
            }
            {searchCity.length > 0 && searchCity.map(item => <View className='item'
              onClick={this.hotCityHandle.bind(this, item)}
            >{item.area_name}</View>)}
          </View>
        </AtIndexes>
      </View>
    )
  }
}

export default SelectCity as ComponentClass<PageOwnProps, PageState>
